//
//  WeekCollectionView.m
//  TableTest
//
//  Created by 众拳科技 on 2017/11/13.
//  Copyright © 2017年 众拳科技. All rights reserved.
//

#import "WeekCollectionView.h"
#import "WeekCollectionViewLayout.h"
#import "WeekCollectionViewCell.h"

@interface WeekCollectionView() <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    
    UICollectionView *_collectionView;
    
    CGFloat _dragStartX;
    
    CGFloat _dragEndX;
}

/**
 记录当前滚动的位置
 */
@property(nonatomic,assign)CGFloat currentPosition;

/**
 记录每一周开始日期和当天的相隔数
 */
@property(nonatomic,assign)NSInteger betwCount;


/**
 记录是否显示动画
 */
@property(nonatomic,assign)BOOL isShowAnimate;


@end

@implementation WeekCollectionView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self buildUI];
    }
    
    return self;
}

- (void)buildUI {
    
    [self addCollectionView];
    
    self.currentPosition = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstDayOfWeekChange:) name:@"DateCollectionViewPageScorll" object:nil];
}

- (void)addCollectionView {
    
    //避免UINavigation对UIScrollView产生的便宜问题
    [self addSubview:[UIView new]];
    WeekCollectionViewLayout *flowLayout = [[WeekCollectionViewLayout alloc] initWithRowCount:1 itemCountPerRow:1];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    _collectionView.showsHorizontalScrollIndicator = false;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[WeekCollectionViewCell class] forCellWithReuseIdentifier:@"WeekCollectionViewCell"];
    _collectionView.userInteractionEnabled = true;
    _collectionView.bounces = YES;
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self addSubview:_collectionView];
    [_collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self);
    }];
}

#pragma mark -

//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _selectedIndex = indexPath.row;
}

#pragma mark CollectionDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 3;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* cellId = @"WeekCollectionViewCell";
    
    WeekCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    
    if (indexPath.item == self.currentPosition) {
     
        cell.betwCount = self.betwCount;
    }
    else{
        
        cell.betwCount = -1;
    }
    
    cell.teachDict = self.teachDict;
    
    cell.hasTeachDict = self.hasTeachDict;
    
    cell.firstDayOfWeek = self.firstDayOfWeek;
    
    cell.gridType = self.gridType;
    
    return  cell;
}

#pragma mark UICollectionDelete
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([self checkNeedScroll:scrollView]) {
        
        NSInteger realIndex = 3 / 2;//移动回第一个
        
        self.currentPosition = realIndex;
        
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:realIndex inSection:0];
        
        [_collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:self.isShowAnimate];
        
        self.isShowAnimate = NO;
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSLog(@"scrollViewDidEndDecelerating  -   End of Scrolling.");
    
    CGPoint positionPoint = scrollView.contentOffset;
    
    positionPoint.y = scrollView.center.y;
    
    NSIndexPath *indexPathNow = [_collectionView indexPathForItemAtPoint:positionPoint];
    
    NSString *dir;
    
    if (indexPathNow.row == self.currentPosition) {
        
        return;
    }
    
    //在这里判断UICollectionView是向右滑动还是向左滑动
    if (indexPathNow.row > self.currentPosition) {
        
        self.firstDayOfWeek = [self getDayWithDate:self.firstDayOfWeek andDayCount:7];
        
        NSLog(@"x= %f,positionRow = %ld  currentPosition = %f",positionPoint.x,(long)indexPathNow.row,self.currentPosition);
        NSLog(@"向➡️➡️➡️➡️➡️➡️➡️");
        
        dir = @"right";
    }
    else{
        
        self.firstDayOfWeek = [self getDayWithDate:self.firstDayOfWeek andDayCount:-7];
        
        NSLog(@"x= %f,positionRow = %ld  currentPosition = %f",positionPoint.x,(long)indexPathNow.row,self.currentPosition);
        NSLog(@"向⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️");
        
        dir = @"left";
    }
    
    
    //这里不管怎么滑动 一直都只是显示中间那个Item
    self.currentPosition = 3 / 2;
    
    [_collectionView reloadData];
    
    //把FirstDayOfWeek 广播出去
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WeekCollectionViewPageScorll" object:nil userInfo:@{@"firstDayOfWeek":self.firstDayOfWeek,@"currentPosition": @(self.currentPosition),@"dir":dir}];
}

//检查是否需要重新移动cell
- (BOOL)checkNeedScroll:(UIScrollView *)scrollView {
    
    CGFloat position = scrollView.contentOffset.x;
    
    CGFloat maxPoisition = scrollView.contentSize.width - self.frame.size.width;
    
    return position <= 0 || position >= maxPoisition;
}


#pragma mark 日期视图滑动的通知
-(void)firstDayOfWeekChange:(NSNotification *)sender{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.isShowAnimate = YES;
        
        //self.currentPosition = 3 / 2;
        
        NSDictionary *userInfo = sender.userInfo;

        self.firstDayOfWeek = [userInfo objectForKey:@"firstDayOfWeek"];

        self.betwCount = [self getNumberOfDayWithDate:self.firstDayOfWeek];

        NSInteger realIndex = [[userInfo objectForKey:@"currentPosition"] integerValue];

        NSIndexPath *newIndexPath = [NSIndexPath indexPathForItem:realIndex inSection:0];

        NSString *dir = [userInfo objectForKey:@"dir"];

        if ([dir isEqualToString:@"left"]) {

            realIndex = (self.currentPosition - 1) < 0 ? 0 : (self.currentPosition - 1);

            newIndexPath = [NSIndexPath indexPathForItem:realIndex inSection:0];

            [_collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }
        else{


            realIndex = (self.currentPosition + 1) >= 3 ? 2 : (self.currentPosition + 1);

            newIndexPath = [NSIndexPath indexPathForItem:realIndex inSection:0];

            [_collectionView scrollToItemAtIndexPath:newIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        }
        
        [_collectionView reloadData];
        
        NSLog(@"self.currentPosition = %f,realIndex = %ld",self.currentPosition,(long)realIndex);
    });
    
}

-(void)setGridType:(NSString *)gridType{
    
    _gridType = gridType;
    
    [_collectionView reloadData];
}

#pragma mark Set
-(void)setFirstDayOfWeek:(NSDate *)firstDayOfWeek{
    
    _firstDayOfWeek = firstDayOfWeek;
    
    self.betwCount = [self getNumberOfDayWithDate:firstDayOfWeek];
}

/**
 获取一个时间与当前时间相差的天数

 @return 天数
 */
-(NSInteger)getNumberOfDayWithDate:(NSDate *)date{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
//    NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    NSDateComponents *comp = [calendar components:NSCalendarUnitDay fromDate:date toDate:[NSDate date] options:NSCalendarWrapComponents];
    
    return comp.day;
}

/**
 日期的加减计算
 @param date 开始时间
 @param count 距离开始时间的天数
 @return 计算后的日期
 */
-(NSDate *)getDayWithDate:(NSDate *)date andDayCount:(NSInteger)count{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *oldComp =[calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitWeekOfYear|NSCalendarUnitWeekOfMonth fromDate:date];
    
    NSInteger day = [oldComp day];
    
    [oldComp setDay:day + count];
    
    NSDate *newDate= [calendar dateFromComponents:oldComp];
    
    return newDate;
}

#pragma mark Get --排课打钩
-(NSMutableDictionary *)teachDict{
    
    if (!_teachDict) {
        
        _teachDict = [[NSMutableDictionary alloc] init];
    }
    
    return _teachDict;
}


-(void)setHasTeachDict:(NSMutableDictionary *)hasTeachDict{
    
    _hasTeachDict = hasTeachDict;
    
    [_collectionView reloadData];
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
